import React, { useState, useEffect, useRef } from 'react';
import { Table, Spin, message, Input, Button } from 'antd';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';

// 模板特征组件
const TemplateFeature = ({ templateId }) => {
  const [loading, setLoading] = useState(false);
  const [featureList, setFeatureList] = useState([]);
  const [allFeatures, setAllFeatures] = useState([]);
  const [featureDetails, setFeatureDetails] = useState({});
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [isMobile, setIsMobile] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const inputRef = useRef(null);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取模板特征列表
  useEffect(() => {
    const fetchTemplateFeatures = async () => {
      if (!templateId) return;
      
      setLoading(true);
      try {
        // 获取模板特征列表
        const response = await axios.get(`${API_BASE_URL}/api/template_feature_value`, {
          params: {
            template_id: templateId
          }
        });
        
        if (response.data && response.data.code === 200) {
          console.log('模板特征列表:', response.data.data);
          // 保存所有特征数据
          const items = response.data.data.items || [];
          setAllFeatures(items);
          
          // 计算总数
          const total = items.length;
          setPagination({
            ...pagination,
            total: total
          });
          
          // 手动实现分页
          updatePageData(items, currentPage);
          
          // 获取每个特征的详细信息
          const featureIds = items.map(item => item.feature_id);
          await fetchFeatureDetails(featureIds);
        } else {
          message.error('获取模板特征列表失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('获取模板特征列表错误:', error);
        message.error('获取模板特征列表失败: ' + (error.message || '网络错误'));
      } finally {
        setLoading(false);
      }
    };

    fetchTemplateFeatures();
  }, [templateId]);

  // 更新当前页数据
  useEffect(() => {
    if (allFeatures.length > 0) {
      updatePageData(allFeatures, currentPage);
    }
  }, [currentPage, pageSize, allFeatures]);

  // 手动分页处理
  const updatePageData = (data, page) => {
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    setFeatureList(currentPageData);
  };

  // 获取特征详情
  const fetchFeatureDetails = async (featureIds) => {
    if (!featureIds || featureIds.length === 0) return;
    
    const detailsMap = {};
    
    try {
      // 并行获取所有特征详情
      const requests = featureIds.map(id => 
        axios.get(`${API_BASE_URL}/api/feature_definition/${id}`)
      );
      
      const responses = await Promise.all(requests);
      
      responses.forEach(response => {
        if (response.data && response.data.code === 200 && response.data.data) {
          const feature = response.data.data;
          detailsMap[feature.id] = feature;
        }
      });
      
      setFeatureDetails(detailsMap);
    } catch (error) {
      console.error('获取特征详情错误:', error);
      message.error('获取特征详情失败: ' + (error.message || '网络错误'));
    }
  };

  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        setCurrentPage(value);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(currentPage + 1);
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    
    try {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    } catch (e) {
      return dateString;
    }
  };

  // 获取表格列定义
  const getColumns = () => {
    const baseColumns = [
      {
        title: '特征编码',
        dataIndex: 'feature_id',
        key: 'feature_code',
        align: 'center',
        ellipsis: true,
        render: (featureId) => {
          const feature = featureDetails[featureId] || {};
          return <span>{feature.feature_code || '-'}</span>;
        }
      },
      {
        title: '特征名称',
        dataIndex: 'feature_id',
        key: 'feature_name',
        align: 'left',
        ellipsis: true,
        render: (featureId) => {
          const feature = featureDetails[featureId] || {};
          return <span>{feature.feature_name || '-'}</span>;
        }
      },
      {
        title: '特征类型',
        dataIndex: 'feature_id',
        key: 'feature_type',
        align: 'center',
        ellipsis: true,
        render: (featureId) => {
          const feature = featureDetails[featureId] || {};
          return <span>{feature.feature_type || '-'}</span>;
        }
      },
      {
        title: '提取方法',
        dataIndex: 'feature_id',
        key: 'extraction_method',
        align: 'center',
        ellipsis: true,
        render: (featureId) => {
          const feature = featureDetails[featureId] || {};
          return <span>{feature.extraction_method || '-'}</span>;
        }
      },
      {
        title: '描述',
        dataIndex: 'feature_id',
        key: 'description',
        align: 'left',
        ellipsis: true,
        render: (featureId) => {
          const feature = featureDetails[featureId] || {};
          return <span>{feature.description || '-'}</span>;
        }
      },
      {
        title: '特征值',
        dataIndex: 'feature_value',
        key: 'feature_value',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{formatDate(text)}</span>
      },
      {
        title: '更新时间',
        dataIndex: 'update_time',
        key: 'update_time',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{formatDate(text)}</span>
      }
    ];
    
    // 移动端只显示核心列
    if (isMobile) {
      return baseColumns.filter(column => 
        ['feature_code', 'feature_name', 'feature_value'].includes(column.key)
      );
    }
    
    return baseColumns;
  };

  // 获取行样式
  const getRowClassName = () => {
    if (featureList.length >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 自定义分页样式
  const customPaginationStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px',
    borderTop: '1px solid #e8e8e8',
    background: '#fff'
  };

  return (
    <Spin spinning={loading}>
      <div className="feature-list-container" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Table
            className={`data-table ${featureList.length >= 10 || isMobile ? 'compact-table' : ''}`}
            dataSource={featureList}
            columns={getColumns()}
            rowKey="id"
            pagination={false}
            rowClassName={getRowClassName}
            size={isMobile || featureList.length >= 10 ? 'small' : 'middle'}
            bordered={true}
            scroll={{ x: isMobile ? 800 : 'max-content' }}
            tableLayout="auto"
            locale={{ emptyText: '暂无数据' }}
          />
        </div>
        
        {/* 自定义分页 */}
        <div style={customPaginationStyle}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span>共 {pagination.total} 条</span>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Button 
              icon={<LeftOutlined />}
              onClick={goPrevPage}
              disabled={currentPage === 1}
              style={{ marginRight: '8px' }}
            />
            
            <Input
              ref={inputRef}
              style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
              value={currentPage}
              onChange={handlePageInputChange}
              onKeyPress={handlePageInputKeyPress}
            />
            
            <Button 
              icon={<RightOutlined />}
              onClick={goNextPage}
              disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
              style={{ marginLeft: '8px', marginRight: '8px' }}
            />
            
            <span style={{ marginLeft: '8px' }}>
              {pageSize} / page
            </span>
          </div>
        </div>
      </div>
    </Spin>
  );
};

export default TemplateFeature; 